package me.suntao.javaio.server.nio2;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * 服务端业务逻辑实现，读取客户端数据
 */
public class ReadCompletionHandler implements CompletionHandler<Integer, ByteBuffer> {
  private AsynchronousSocketChannel socketChannel;

  public ReadCompletionHandler(AsynchronousSocketChannel socketChannel) {
    if(this.socketChannel==null) {
      this.socketChannel = socketChannel;
    }
  }

  @Override public void completed(Integer result, ByteBuffer attachment) {
    //获取客户端数据
    attachment.flip();
    byte[] body = new byte[attachment.remaining()];
    attachment.get(body);
    try {
      String request = new String(body,"UTF-8");
      doWrite(request);
      System.out.println(request);
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }

  }

  @Override public void failed(Throwable exc, ByteBuffer attachment) {
    try {
      socketChannel.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  private void doWrite(String response){
    if(response==null){
      return;
    }
    byte[] bytes = response.getBytes();
    final ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
    writeBuffer.put(bytes);
    writeBuffer.flip();
    socketChannel.write(writeBuffer, writeBuffer, new CompletionHandler<Integer, ByteBuffer>() {
      @Override public void completed(Integer result, ByteBuffer attachment) {
        //如果没发完，接着发。
        if(attachment.hasRemaining()){
          socketChannel.write(attachment,attachment,this);
        }
      }

      @Override public void failed(Throwable exc, ByteBuffer attachment) {
        try {
          socketChannel.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    });
  }
}
